import { request, downloadBlobFile } from 'src/utils';

export interface MenuDto {
  menuId: IdType; // 菜单ID
  parentId: IdType; // 上级ID
  menuName: string; // 菜单名称
  menuType: number; // 菜单类型
  menuPath: string; // 菜单地址
  permission?: string; // 权限标识
  icon?: string; // 菜单图标
  sortNo?: number; // 排序号
  remark?: string; // 备注说明
  children: MenuDto[];
}

const baseUrl = '/api/system/menu';

/**
 * 查单个
 */
export function readData(menuId: IdType): Promise<MenuDto> {
  return request.get(baseUrl + '/' + menuId);
}

/**
 * 查集合
 */
export function queryList(query: PageQuery): Promise<PageResult<MenuDto>> {
  return request.get(baseUrl, { params: query });
}

/**
 * 查菜单树
 */
export function getMenuTree(query: BaseQuery = {}): Promise<MenuDto[]> {
  return request.get(baseUrl + '/tree', { params: query });
}

/**
 * 新增，修改
 */
export function saveOrUpdate(menu: MenuDto): Promise<MenuDto> {
  return menu.menuId ? request.put(baseUrl + '/' + menu.menuId, menu) : request.post(baseUrl, menu);
}

/**
 * 删除
 */
export function deleteByIds(ids: IdType[]): Promise<void> {
  return request.delete(baseUrl, { params: { ids } });
}

/**
 * 导出
 */
export function exportData(query: PageQuery): Promise<void> {
  return new Promise((resolve, reject) => {
    request
      .get(baseUrl + '/export', { params: query, responseType: 'blob' })
      .then((res) => {
        downloadBlobFile(res);
        resolve();
      })
      .catch((err) => reject(err));
  });
}

export default { readData, queryList, saveOrUpdate, deleteByIds, exportData } as CrudApi<MenuDto>;
